using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// TODO: GetAge should accept some format-string...

namespace Konst3d.Efficiency
{
	public static class DateTimeExtender
	{
		public static ShortDate GetShortDate(this DateTime date)
		{
			return new ShortDate(date);
		}

		public static string GetAge(this DateTime born)
		{
			return GetAge(born, DateTime.Now);
		}

		public static string GetAge(this DateTime born, DateTime now)
		{
			var month = (now.Year - born.Year) * 12 + now.Month - born.Month;
			int days = 0;

			if (now.Day < born.Day)
			{
				month -= 1;
				days = DateTime.DaysInMonth(born.Year, born.Month) - born.Day + now.Day + 1;
			}
			else
			{
				days = now.Day - born.Day + 1;
			}

			var years = month / 12;
			month -= years * 12;

			var str = new StringBuilder();

			if (years > 0)
			{
				str.AppendFormat("{0} {1}", years, years > 1 ? "years" : "year");
			}

			if (month > 0)
			{
				if (str.Length > 0)
				{
					str.Append(" ");
				}

				str.AppendFormat("{0} {1}", month, month > 1 ? "months" : "month");
			}

			if (days > 0)
			{
				if (str.Length > 0)
				{
					str.Append(" ");
				}

				str.AppendFormat("{0} {1}", days, days > 1 ? "days" : "day");
			}

			return str.ToString();
		}

		public static DateTime GetFirstDayOfWeek(this DateTime date)
		{
			return date.AddDays(-(double)(date.DayOfWeek == DayOfWeek.Sunday ? 6 : (int)date.DayOfWeek - 1));
		}

		public static DateTime GetLastDayOfWeek(this DateTime date)
		{
			return date.AddDays((double)(date.DayOfWeek == DayOfWeek.Sunday ? 0 : 7 - (int)date.DayOfWeek));
		}
	}
}
